package com.chatai.controller;

import com.chatai.service.AIService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/ai")
public class AIController {
    private static final Logger logger = LoggerFactory.getLogger(AIController.class);

    @Autowired
    private AIService aiService;

    /**
     * 获取可用的AI模型列表
     */
    @GetMapping("/models")
    public ResponseEntity<List<Map<String, String>>> getAvailableModels() {
        try {
            logger.info("开始获取AI模型列表");
            List<Map<String, String>> models = aiService.getAvailableModels();
            logger.info("获取AI模型列表成功，共 {} 个模型", models.size());
            return ResponseEntity.ok(models);
        } catch (Exception e) {
            logger.error("获取AI模型列表失败: {}", e.getMessage(), e);
            return ResponseEntity.status(500).body(List.of(
                    Map.of("id", "qwen-turbo", "name", "通义千问 Turbo", "description", "高性能模型", "type", "free")
            ));
        }
    }

    /**
     * 发送消息给AI并获取回复，支持指定模型
     */
    @PostMapping("/chat")
    public ResponseEntity<Map<String, String>> chatWithAI(
            @RequestBody Map<String, String> request) {
        try {
            logger.info("接收到AI聊天请求: {}", request);
            
            // 验证请求体
            if (request == null) {
                logger.warn("请求体为空");
                return ResponseEntity.badRequest().body(Map.of("error", "请求体不能为空"));
            }
            
            String message = request.get("message");
            String modelId = request.getOrDefault("modelId", "qwen-turbo"); // 默认使用qwen-turbo模型
            
            if (message == null || message.trim().isEmpty()) {
                logger.warn("消息内容为空");
                return ResponseEntity.badRequest().body(Map.of("error", "消息不能为空"));
            }
            
            logger.info("调用AI服务获取响应，模型: {}, 消息长度: {}", modelId, message.length());
            String response = aiService.getAIResponse(message, modelId);
            
            Map<String, String> result = new HashMap<>();
            result.put("response", response);
            result.put("modelId", modelId);
            result.put("success", "true");
            
            logger.info("AI聊天请求处理成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("AI聊天请求处理失败: {}", e.getMessage(), e);
            return ResponseEntity.status(500).body(Map.of(
                    "error", "处理请求时发生错误: " + e.getMessage(),
                    "success", "false"
            ));
        }
    }
}